/**
 * @date: 2025/3/22
 * @fileName: user
 * @Description: 用户状态
 */
import { acceptHMRUpdate, defineStore } from 'pinia';
import { ApiLogin } from '@/api/system/auth.ts';
import { useUserStore } from '@/stores/modules/user.ts';
import { useWebsocketStore } from '@/stores/modules/websocket.ts';
import { ApiUserLogout } from '@/api/system/user.ts';
import { Message } from '@arco-design/web-vue';
import { router } from '@/router';

import { resetAllStores } from '@/stores';

type Token = null | string;

interface AuthState {
	/**
	 * 登录 accessToken
	 */
	accessToken: Token;
	/**
	 * 登录 accessToken
	 */
	refreshToken: Token;
}

export const useAuthStore = defineStore('app-auth', {
	state: (): AuthState => ({
		accessToken: null,
		refreshToken: null,
	}),
	actions: {
		/**
		 * 设置 access token
		 * @param token
		 */
		setAccessToken(token: Token) {
			this.accessToken = token;
		},

		/**
		 * 设置 refresh token
		 * @param token
		 */
		setRefreshToken(token: Token) {
			this.refreshToken = token;
		},

		/**
		 * 登录
		 * @param params
		 * @param options
		 */
		async login(params: any, options?: any) {
			const data = await ApiLogin(params.form, options);

			const userStore = useUserStore();

			// 设置token
			this.setAccessToken(data.accessToken);
			this.setRefreshToken(data.refreshToken);

			//  设置个人租户
			userStore.setTenant(params.tenant);

			// 设置用户信息的租户列表
			userStore.setTenantList(params.tenants);

			await router.replace({ path: '/' });
			Message.success('登录成功');
		},

		/**
		 * 退出登录
		 */
		async logout() {
			await ApiUserLogout();
			useWebsocketStore().closeWebsocket(); // 断开im连接
			resetAllStores();
			await router.replace('/login');
		},
	},
	persist: {
		pick: ['accessToken', 'refreshToken'],
	},
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
	hot.accept(acceptHMRUpdate(useAuthStore, hot));
}
